package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.utils.JodaUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by Joe on 2018/1/24.
 */
public class UserEnableHandler extends SessionHandler<UserEnableParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserEnableParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getTargetUserId(), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                User user = userDao.findById(params.getTargetUserId(), User.class);
                if (null == user) return errorMessage(MessageCode.code_404);
                user.setDisable(params.isEnable() ? 0 : JodaUtils.getTimestamp());
                userDao.saveOrUpdate(user);
                return successMessage(new UserModel(user, 2, globalVariablesService.getGlobalRule().getDefaultAvatar()));
            }
        });
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
